<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>安全设置</span>
      </div>
      <!-- 安全设置的容器 -->
      <div class="setting-box">
        <el-table :data="tableData" style="width: 100%" :show-header="false">
          <!-- 认证类型 -->
          <el-table-column prop="safeType" width="80"> </el-table-column>
          <!-- 认证状态 -->
          <el-table-column prop="status" width="80">
            <template slot-scope="scope">
              <!-- scope:作用域插槽,访问了子组件传递过来的数据 -->
              {{ scope.row.status }}
              <div :class="{ successStatus: scope.row.status }">
                <!-- 认证图标 -->
                <i class="el-icon-success"></i>
              </div>
            </template>
          </el-table-column>
          <!-- 认证的值 ，formatter根据返回对象来显示值 -->
          <el-table-column prop="value" width="480" :formatter="formatValue">
          </el-table-column>
          <!-- 去认证的按钮 -->
          <el-table-column>
            <template slot-scope="scope">
              <el-button type="text" v-if="checkType(scope.row) == '认证成功'"
                >认证成功</el-button
              >
              <el-button
                type="text"
                @click="authRealName"
                v-else-if="checkType(scope.row) == '去认证'"
                >去认证</el-button
              >
              <el-button
                type="text"
                @click="MobilePhone"
                v-else-if="checkType(scope.row) == '更换手机号'"
                >更换手机号</el-button
              >
              <el-button
                type="text"
                @click="OnChangeLonginPassWorld"
                v-else-if="checkType(scope.row) == '修改登录密码'"
                >修改登录密码</el-button
              >

              <el-button
                type="text"
                @click="OnResetPaymentPassword"
                v-else-if="checkType(scope.row) == '去设置'"
                >去设置</el-button
              >

              <!-- 更换支付密码 -->
              <el-button
                type="text"
                @click="OnChangePaymentPIN"
                v-else-if="checkType(scope.row) == '修改支付密码'"
                >修改支付密码</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 实名认证 -->
    <el-dialog
      title="实名认证"
      :visible.sync="dialogFormVisible"
      width="30%"
      center
    >
      <el-form
        :rules="rules"
        ref="realNameForm"
        :model="realNameForm"
        :label-width="formLabelWidth"
      >
        <el-form-item label="姓名" prop="realName">
          <el-input
            v-model="realNameForm.realName"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="身份证号码" prop="idNum">
          <el-input v-model="realNameForm.idNum" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitrealname('realNameForm')"
          >添加</el-button
        >
        <el-button
          @click="dialogFormVisible = false || onCancel('realNameForm')"
          >取 消</el-button
        >
      </div>
    </el-dialog>

    <!-- 更换手机号 -->
    <el-dialog
      title="更换手机号"
      :visible.sync="dialogFormVisiblePhone"
      width="30%"
      center
    >
      <el-form
        :rules="rules"
        ref="RealNameAuthentication"
        :model="RealNameAuthentication"
        :label-width="phone_formLabelWidth"
      >
        <el-form-item label="旧手机号" prop="oldPhone">
          <el-input
            style="width: 125px"
            readonly
            v-model="RealNameAuthentication.oldPhone"
            autocomplete="off"
            >{{ RealNameAuthentication.oldPhone }}</el-input
          >
        </el-form-item>

        <el-form-item label="旧手机号验证码" prop="oldPhoneCode">
          <el-input
            style="width: 100px"
            v-model="RealNameAuthentication.oldPhoneCode"
            prop="Code"
          ></el-input>
          <el-button
            style="margin-left: 5px"
            @click="sendMsg"
            :disabled="!accountStatus.phone || !sendBtnAble"
            type="primary"
            >{{ sendBtnTxt }}</el-button
          >
        </el-form-item>

        <el-form-item label="新手机号" prop="newPhone">
          <el-input
            style="width: 125px"
            v-model="RealNameAuthentication.newPhone"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="新手机号验证码" prop="NewPhoenCode">
          <el-input
            style="width: 100px"
            v-model.number="RealNameAuthentication.NewPhoenCode"
            autocomplete="off"
            prop="code"
          ></el-input>
          <el-button
            style="margin-left: 5px"
            @click="sendMsg"
            :disabled="!accountStatus.phone || !sendBtnAble"
            type="primary"
            >{{ sendBtnTxt }}</el-button
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitrealphone('RealNameAuthentication')"
          >更改</el-button
        >
        <el-button
          @click="
            dialogFormVisiblePhone = false || onCancel('RealNameAuthentication')
          "
          >取 消</el-button
        >
      </div>
    </el-dialog>

    <!-- 更改登录密码 -->
    <el-dialog
      title="更改登录密码"
      :visible.sync="dialogFormVisibleChangeLonginPassworld"
      width="30%"
      center
    >
      <el-form
        :rules="rules"
        ref="ChangeLonginPasswold"
        :model="ChangeLonginPasswold"
        :label-width="phone_formLabelWidth"
      >
        <el-form-item label="旧手机号" prop="oldPhone">
          <el-input
            style="width: 125px"
            readonly
            v-model="ChangeLonginPasswold.oldPhone"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="旧密码" prop="old_passworld">
          <el-input
            style="width: 125px"
            show-password
            v-model="ChangeLonginPasswold.old_passworld"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="新密码" prop="new_passworld">
          <el-input
            style="width: 125px"
            show-password
            v-model="ChangeLonginPasswold.new_passworld"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <el-input
            style="width: 100px"
            v-model.number="ChangeLonginPasswold.code"
            autocomplete="off"
            prop="code"
          ></el-input>
          <el-button
            style="margin-left: 5px"
            @click="sendMsg"
            :disabled="!accountStatus.phone || !sendBtnAble"
            type="primary"
            >{{ sendBtnTxt }}</el-button
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitsetloginpassworld('ChangeLonginPasswold')"
          >更改</el-button
        >
        <el-button
          @click="
            dialogFormVisibleChangeLonginPassworld =
              false || onCancel('ChangeLonginPasswold')
          "
          >取 消</el-button
        >
      </div>
    </el-dialog>

    <!-- 设置支付密码 -->
    <el-dialog
      title="设置支付密码"
      :visible.sync="dialogFormVisibleSetAPaymentPassword"
      width="30%"
      center
    >
      <el-form
        :rules="rules"
        ref="SetPaymentPassword"
        :model="SetPaymentPassword"
        :label-width="formLabelWidth"
      >
        <el-form-item label="手机号" prop="phone">
          <el-input
            style="width:125px"
            readonly
            v-model="SetPaymentPassword.phone"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="code">
          <el-input
            style="width:80px"
            v-model.number="SetPaymentPassword.code"
            autocomplete="off"
            prop="code"
          ></el-input>
          <el-button
            style="margin-left:5px"
            @click="sendMsg"
            :disabled="!accountStatus.phone || !sendBtnAble"
            type="primary"
          >
            {{ sendBtnTxt }}
          </el-button>
        </el-form-item>

        <el-form-item label="支付密码" prop="payment_password">
          <el-input
            style="width:120px"
            show-password
            v-model="SetPaymentPassword.payment_password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitsetpassworld('SetPaymentPassword')"
          >确定</el-button
        >
        <el-button
          @click="
            dialogFormVisibleSetAPaymentPassword =
              false || onCancel('SetPaymentPassword')
          "
          >取 消</el-button
        >
      </div>
    </el-dialog>

    <!-- 更改支付密码 -->
    <el-dialog
      title="更改支付密码"
      :visible.sync="dialogFormVisibleResetPaymentPassword"
      width="30%"
      center
    >
      <el-form
        :rules="rules"
        ref="ChangePIN"
        :model="ChangePIN"
        :label-width="phone_formLabelWidth"
      >
        <el-form-item label="手机号" prop="ChangePIN_phone">
          <el-input
            style="width:125px"
            readonly
            v-model="ChangePIN.ChangePIN_phone"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="旧支付密码" prop="ChangePIN_old_passworld">
          <el-input
            style="width:100px"
            show-password
            v-model="ChangePIN.ChangePIN_old_passworld"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="新支付密码" prop="ChangePIN_new_passworld">
          <el-input
            style='width:100px'
            show-password
            v-model="ChangePIN.ChangePIN_new_passworld"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="ChangePIN_code">
          <el-input
            style="width:80px"
            v-model.number="ChangePIN.ChangePIN_code"
            autocomplete="off"
            prop="code"
          ></el-input>
          <el-button
            style="margin-left: 5px;"
            @click="sendMsg"
            :disabled="!accountStatus.phone || !sendBtnAble"
            type="primary"
            >{{ sendBtnTxt }}</el-button
          >
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPIN('ChangePIN')"
          >修改</el-button
        >
        <el-button
          @click="
            dialogFormVisibleResetPaymentPassword =
              false || onCancel('ChangePIN')
          "
          >取 消</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapActions } from "vuex";

export default {
  name: "WorkspaceJsonSafe",

  data() {
    // 自定义身份证的校验器
    var realName = (rule, value, callback) => {
      console.log(rule, value, callback);
      if (value === "") {
        callback(new Error("名字不能为空"));
      }
      setTimeout(() => {
        const regAmount = /^[\u4e00-\u9fa5]{2,4}$/; //2-4个中文字符正则
        console.log(regAmount.test(value));
        if (regAmount.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的名字"));
        }
      }, 500);
    };
    // 自定义身份证的校验器
    var idNum = (rule, value, callback) => {
      console.log(rule, value, callback);
      if (value === "") {
        callback(new Error("身份证不能为空"));
      }
      setTimeout(() => {
        const regAmount = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
        console.log(regAmount.test(value));
        if (regAmount.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的身份证"));
        }
      }, 500);
    };
    // 自定义借款金额校验器
    var checkAmount = (rule, value, callback) => {
      console.log(rule, value, callback);
      if (value === "") {
        callback(new Error("手机号不能为空"));
      }
      setTimeout(() => {
        const regAmount = /^1[34578]\d{9}$/;
        console.log(regAmount.test(value));
        if (regAmount.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的手机号"));
        }
      }, 500);
    };
    var checkcode = (rule, value, callback) => {
      console.log("1", value);
      if (value === "") {
        callback(new Error("验证码不能为空"));
      }
      setTimeout(() => {
        const regAmount = /\d{4}$/;
        console.log(regAmount.test(value));
        if (regAmount.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确的验证码"));
        }
      }, 500);
    };
    var checkPassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("支付密码不能为空"));
      }
      setTimeout(() => {
        const regAmount = /\d{6}$/;
        console.log(regAmount.test(value));
        if (regAmount.test(value)) {
          callback();
        } else {
          callback(new Error("请输入6位的支付密码"));
        }
      }, 500);
    };
    return {
      // 默认可以发送验证码
      sendBtnAble: true,
      // 计时器多少秒
      conter: 10,
      // 验证码按钮
      sendBtnTxt: "发送验证码",
      // 输入框宽度
      formLabelWidth: "100px",
      phone_formLabelWidth: "120px",
      // 控制实名认证的对话框的开关
      dialogFormVisible: false,
      // 更换手机号的开关
      dialogFormVisiblePhone: false,
      // 更换登录密码的开关
      dialogFormVisibleChangeLonginPassworld: false,
      // 设置支付密码的开关
      dialogFormVisibleSetAPaymentPassword: false,

      // 更换支付密码的开关
      dialogFormVisibleResetPaymentPassword: false,

      // 数据
      // 实名认证
      realNameForm: {
        // 真实姓名
        realName: "",
        // 身份证号码
        idNum: "",
      },
      // 更换手机号
      RealNameAuthentication: {
        // 旧手机号
        oldPhone: "",
        // 旧手机号验证码
        oldPhoneCode: "",
        // 新手机号
        newPhone: "",
        // 新手机号的验证码
        NewPhoenCode: "",
      },
      // 更改登录密码
      ChangeLonginPasswold: {
        // 旧手机号
        oldPhone: "",
        // 旧密码
        old_passworld: "",
        // 新密码
        new_passworld: "",
        // 手机验证码
        code: "",
      },
      // 设置支付密码
      SetPaymentPassword: {
        // 手机号
        phone: "",
        // 验证码
        code: "",
        // 支付密码
        payment_password: "",
      },

      // 更换支付密码
      ChangePIN: {
        // 手机号
        ChangePIN_phone: "",
        // 旧的支付密码
        ChangePIN_old_passworld: "",
        // 新的支付密码
        ChangePIN_new_passworld: "",
        // 验证码
        ChangePIN_code: "",
      },
      // 自定义的校验器（这里的验证器要和v-modle的名字一样）
      rules: {
        // 真实姓名
        realName: [{ validator: realName, trigger: "blur" }],
        // 身份证号码
        idNum: [{ validator: idNum, trigger: "blur" }],
        // 旧手机号码
        oldPhone: [
          // validator接自定义校验器，trigger: 'blur'当鼠标失去焦点时
          { validator: checkAmount, trigger: "blur" },
        ],
        // 新手机号码
        newPhone: [{ validator: checkAmount, trigger: "blur" }],
        // 旧手机的验证码
        oldPhoneCode: [{ validator: checkcode, trigger: "blur" }],
        // 新手机的验证码
        NewPhoenCode: [{ validator: checkcode, trigger: "blur" }],
        // 密码
        passworld: [{ required: true, message: "密码不能为空" }],
        // 新手机号码的验证码
        old_passworld: [{ validator: checkcode, trigger: "blur" }],
        // 旧手机号的密码
        oldPassworld: [{ required: true, message: "密码不能为空" }],
        // 新手机号的密码
        new_passworld: [{ required: true, message: "密码不能为空" }],
        // 手机号验证码
        code: [{ validator: checkcode, trigger: "blur" }],
        // 支付密码
        payment_password: [{ validator: checkPassword, trigger: "blur" }],
        // 更换支付密码的手机号
        ChangePIN_phone: [{ validator: checkAmount, trigger: "blur" }],
        // 更换支付密码的旧支付密码
        ChangePIN_old_passworld: [
          { validator: checkPassword, trigger: "blur" },
        ],
        // 更换支付密码的新支付密码
        ChangePIN_new_passworld: [
          { validator: checkPassword, trigger: "blur" },
        ],
        // 更换支付密码的验证码
        ChangePIN_code: [{ validator: checkcode, trigger: "blur" }],
      },
      tableData: [
        {
          safeType: "用户名",
          status: "",
          value: "123",
        },
        {
          safeType: "实名认证",
          status: "",
          value: "123",
        },
        {
          safeType: "手机认证",
          status: "",
          value: "123",
        },
        {
          safeType: "登录密码",
          status: "",
          value: "123",
        },
        {
          safeType: "支付密码",
          status: "",
          value: "123",
        },
      ],
    };
  },
  computed: {
    ...mapGetters(["accountStatus"]),
  },
  // 在页面创建成功的时候，调用一下事件
  created() {
    console.log(this.accountStatus.phone);
    this.RealNameAuthentication.oldPhone = this.accountStatus.phone;
    this.ChangeLonginPasswold.oldPhone = this.accountStatus.phone;
    this.SetPaymentPassword.phone = this.accountStatus.phone;
    this.ChangePIN.ChangePIN_phone = this.accountStatus.phone;
    this.getStatus();
  },
  methods: {
    ...mapActions({
      getSmsCode: "user/getSmsCode",
      loanapply: "loan/loanapply",
      // 实名认证
      realNameAuth: "user/realNameAuth",
      // 更换手机号码
      realphone: "user/realphone",
      // 设置支付密码
      setpassworld: "user/setpassworld",
      // 修改登录密码
      realpassworld: "user/realpassworld",
      // 更换支付密码
      changepinL: "user/changepin",
    }),
    // 发送验证码
    sendMsg() {
      // this.isRightPhone = false
      this.getSmsCode({ phone: this.accountStatus.phone })
        .then((res) => {
          console.log(res);
          this.sendBtnAble = false;
          this.$notify({
            title: "验证码",
            message: res.sms_Code,
            type: "success",
          });
          this.countDown(); // 调用函数
        })
        .catch((err) => {
          this.sendBtnAble = true; // 出错的话，就继续可以点击
        });
    }, // 倒计时开始
    countDown() {
      this.timer = setInterval(() => {
        // 计时器（默认是空的）
        this.sendBtnTxt = `${this.conter}秒`; // 进行文字替换
        this.conter--; // 每一次减1秒
        if (this.conter < 0) {
          // 计时器小于0的时候就重置计时器
          this.reset();
        }
      }, 1000);
    }, // 重置计时器
    reset() {
      this.sendBtnAble = true; // 将按钮改为可点击
      this.sendBtnTxt = "发送验证码"; // 将倒计时改为文字
      if (this.timer) {
        // 判断有没有计时器
        clearInterval(this.timer); // 清空计时器
        this.conter = 10; // 下一次点击从第10秒开始
        this.timer = null; // 继续将计时器改为空
      }
    },
    // 提交身份证表单
    submitrealname(formname) {
      this.$refs[formname].validate((valid) => {
        console.log(valid);
        console.log(formname);
        if (valid) {
          alert("成功");
          this.realNameAuth(this.realNameForm).then((res) => {
            this.onCancel(formname);
            // 关闭实名认证的对话框的开关
            (this.dialogFormVisible = false), this.getStatus();
          });
        } else {
          alert("error");
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 提交更换手机号的表单
    submitrealphone(formname) {
      this.$refs[formname].validate((valid) => {
        console.log(valid);
        console.log(formname);
        if (valid) {
          alert("成功");
          this.realphone(this.RealNameAuthentication).then((res) => {
            this.onCancel(formname);
            this.dialogFormVisiblePhone = false;
            this.getStatus();
          });
        } else {
          alert("error");
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 修改登录密码
    submitsetloginpassworld(formname) {
      this.$refs[formname].validate((valid) => {
        console.log(valid);
        console.log(formname);
        if (valid) {
          this.realpassworld(this.ChangeLonginPasswold).then((res) => {
            alert("成功修改了登录密码");
            this.onCancel(formname);
            // 将更换登录密码的面板关闭
            (this.dialogFormVisibleChangeLonginPassworld = false),
              this.getStatus();
          });
        } else {
          ~alert("error");
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 设置支付密码
    submitsetpassworld(formname) {
      this.$refs[formname].validate((valid) => {
        console.log(valid);
        console.log(formname);
        if (valid) {
          this.setpassworld(this.SetPaymentPassword).then((res) => {
            alert("成功设置了支付密码");
            this.onCancel(formname);
            // 将设置支付密码的开关关闭
            this.dialogFormVisibleSetAPaymentPassword = false;
            this.getStatus();
          });
        } else {
          alert("error");
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 更换支付密码
    submitPIN(formname) {
      this.$refs[formname].validate((valid) => {
        console.log(valid);
        console.log(formname);
        if (valid) {
          this.changepinL(this.ChangePIN).then((res) => {
            alert("成功的更换了支付密码");
            this.onCancel(formname);
            // 将设置支付密码的开关关闭
            this.dialogFormVisibleResetPaymentPassword = false;
            this.getStatus();
          });
        } else {
          alert("error");
          console.log("error submit!!");
          return false;
        }
      });
    },

    // 隐藏弹出表单和重置表单
    onCancel(formname) {
      console.log(formname);
      // restFields对整个表单进行进行重置
      this.$refs[formname].resetFields();
    },
    // 去实名认证
    authRealName() {
      // 将弹窗显示出来
      this.dialogFormVisible = true;
    },
    // 手机更改
    MobilePhone() {
      // 将弹窗显示出来
      this.dialogFormVisiblePhone = true;
    },
    // 更换手机号
    OnChangeLonginPassWorld() {
      this.dialogFormVisibleChangeLonginPassworld = true;
    },

    // 设置支付密码
    OnResetPaymentPassword() {
      this.dialogFormVisibleSetAPaymentPassword = true;
    },

    // 更换支付密码
    OnChangePaymentPIN() {
      this.dialogFormVisibleResetPaymentPassword = true;
    },
    // 检查类型并返回操作的提示
    checkType(row) {
      if (row.safeType == "实名认证") {
        if (row.value) {
          return "认证成功";
        } else {
          return "去认证";
        }
      }
      if (row.safeType == "手机认证") {
        return "更换手机号";
      }
      if (row.safeType == "登录密码") {
        return "修改登录密码";
      }
      if (row.safeType == "支付密码") {
        if (row.value) {
          return "修改支付密码";
        } else {
          return "去设置";
        }
      }
    },
    // 格式化认证状态的值
    formatValue(row) {
      console.log(row);
      if (row.safeType == "用户名") {
        console.log(row.value);
        return row.value;
      }
      if (row.safeType == "实名认证") {
        // 三元表达式,如果row.status为真（?）的话，就显示已认证，如果是假（:）的话，就显示未认证
        return row.status ? "已认证" : "未认证";
      }
      if (row.safeType == "手机认证") {
        return row.status ? row.value : "未认证";
      }
      if (row.safeType == "登录密码") {
        return row.status ? "已设置 " : "未设置";
      }
      if (row.safeType == "支付密码") {
        return row.status ? "已认证 " : "未认证";
      }
    },
    // 获取用户认证状态，并设置到表格里面
    getStatus() {
      var count = 0;
      // 循环的获取用户的认证状态的状态和值，保存到tabledata里面
      console.log("用户认证状态的对象", this.accountStatus);
      for (const key in this.accountStatus) {
        if (count < 5) {
          // console.log(count,key)
          this.tableData[count].status = this.accountStatus[key];
          this.tableData[count].value = this.accountStatus[key];
          count++;
        }
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  .box-card {
    width: 85%;
    margin: 0px auto;
    .el-icon-success {
      font-size: 20px;
    }
  }
  .successStatus {
    color: lightgreen;
  }
}
</style>
